<template>
  <div>
    <allHead>
        <template v-slot:mid>题目生成助手</template>
    </allHead>
    <div class="bd">
      <div class="bot answer one">
        AI:
        <span>您好！将为您生成{{ book.editions }}-{{ book.textClass }}{{ book.term }}-{{ book.subject }}-{{ book.unit }}-{{
          book.content }}的相关题目，您可以指导我修改。</span>
      </div>
      <div class="chat" v-for="item in conversation">

        <div class="user question" v-if="item.role === 'user'">
          <span>{{ item.content }}</span>
        </div>
        <div class="bot answer" v-if="item.role === 'assistant'">
          AI:
          <!-- <span v-html="item.content"></span> -->

          <div class="question-item" v-for="(question, index) in questionStore.allquestion.allquestion" :key="index" >
            <div class="choice" v-if="question.type === 'choice'" >
              <h3>{{ question.question }}</h3>
              <ul>
                <li v-for="(option, optIndex) in question.options" :key="optIndex">
                  {{ String.fromCharCode(65 + optIndex) }}. {{ option }}
                </li>
              </ul>
              <div class="answer-block">答案：<span class="correct">{{ question.answer }}</span></div>
              <div class="explanation">解析：{{ question.explanation }}</div>
            </div>

            <div class="blank" v-else-if="question.type === 'blank'" >
              <h3>{{ question.question.replace('_', '_______') }}</h3>
              <div class="answer-block">答案：<span class="correct">{{ question.answer }}</span></div>
              <div class="explanation">解析：{{ question.explanation }}</div>
            </div>

            <div class="short-answer" v-else-if="question.type === 'short_answer'" >
              <h3>{{ question.question }}</h3>
              <div class="answer-block">答案：<span class="correct">{{ question.answer }}</span></div>
              <div class="explanation">解析：{{ question.explanation }}</div>
            </div>
          </div>

          <div class="sure" v-if="finish && item.content">
            <van-button type="primary" size="small" to="question" block>生成题目</van-button>
          </div>

        </div>

      </div>
      <div v-if="!finish">
        <van-loading vertical>
          <template #icon>
            <van-icon name="star-o" size="30" />
          </template>
          生成中，请稍等...
        </van-loading>
      </div>
    </div>

    <div class="ft">
      <div class="input">
        <input type="text" placeholder="请输入您的问题" v-model="question">
        <button @click="send">发送</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import allHead from "@/components/allHead.vue";
import { onMounted, ref } from 'vue'
import axios from 'axios'
import { useBookStore } from '@/stores/bookStore.js';
import {useQuestionStore} from '@/stores/qusetionStore.js';

const bookStore = useBookStore();

const questionStore = useQuestionStore();

const book = ref(bookStore.book.book || {})

const conversation = ref([])

const question = ref('')

const finish = ref(true)

const questions = ref([]);

// 发送请求
onMounted(async () => {

  const msg = {
    role: "assistant",
    content: `帮我生成${book.value.editions}-${book.value.textClass}${book.value.term}-${book.value.subject}-${book.value.unit}-${book.value.content}的5-15道相关题目。包括选择题（choice），填空题（blank），简答题（short_answer），以例如如下格式的josn字段返回给我
      [{"type": "choice", "question": "选择题：", "options": ["", "", "xx", ""], "answer": "xx", "explanation": ""},
    {"type": "blank", "question": "填空题：", "answer": "", "explanation": ""},
    {"type": "short_answer", "question": "简答题：", "answer": "", "explanation": ""}
    }]`
  }

  postData(msg);

  // console.log('请求完成')
  // conversation.value.push({
  //   role: "assistant",
  //   content: res.data.content
  // })
  //console.log(res.data.content,514654654)
})

// 发送请求
const send = async () => {
  if (question.value.trim() === "") return;

  // 添加用户消息到对话
  const userMessage = {
    role: "user",
    content: question.value
  };
  conversation.value.push(userMessage);

  // 清空输入框
  question.value = "";

  // 构造请求消息
  const msg = {
    role: "user",
    content: question.value
  };

  postData(msg);
};

const postData = async (msg) => {
  finish.value = false;
  try {
    const response = await fetch('http://121.43.122.26:3001/openai/chat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(msg)
    });


    if (!response.ok) {
      throw new Error('请求失败');
    }

    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let buffer = '';

    // 流式读取数据
    while (true) {
      const { done, value } = await reader.read();

      //数据流读取完毕
      if (done) {
        finish.value = true;
        //??????
        //console.log(conversation)
        break;
      }


      buffer += decoder.decode(value, { stream: true });

      // 按行分割数据并更新页面

      const lines = buffer.split(/,\n|\n?\`\`\`json\n?\[|\]\n/);  
      buffer = lines.pop(); // 保留未完成的最后一行




      for (const line of lines) {
        try {
          

          if (line.endsWith(',')) {
            line = line.slice(0, -1);  // 删除最后一个字符
          }

          // 尝试解析为单个题目对象
          const questionObj = JSON.parse(line);
          console.log(questionObj)
          // 添加到questions数组
          questions.value = [...questions.value, questionObj];
        } catch (error) {
          console.error('解析题目失败:', error);

          // 如果解析失败，尝试作为完整数组解析（兼容旧格式）
          // try {
          //   const questionArray = JSON.parse(line);
          //   questions.value = [...questions.value, ...questionArray];
          // } catch (e) {
          //   console.error('完全解析失败:', e);
          // }
        }
      }
    }


    // 处理剩余的缓冲区数据
    if (buffer) {
      appendContent(buffer);
    }
  } catch (error) {
    console.error('请求失败', error);
    appendContent('请求失败，请稍后重试');
  }

  //console.log(questions.value)
  // 保存题目
  questionStore.setQuestion({
      allquestion: questions.value
  })

}

// 追加内容到对话
const appendContent = (content) => {
  const lastMessage = conversation.value[conversation.value.length - 1];

  if (lastMessage && lastMessage.role === 'assistant') {
    // 如果最后一条消息是 AI 的回复，则追加内容
    lastMessage.content += content;
  } else {
    // 否则创建一条新的 AI 回复消息
    conversation.value.push({
      role: "assistant",
      content: content
    });
  }
};


</script>

<style lang="css" scoped>
.bd {
  height: calc(100vh - 160px);
  background: #f5f7fa;
  overflow-y: auto;
  padding: 1rem 1rem 5rem;
  box-sizing: border-box;
}

.chat {
  margin: 1.5rem 0;
}

.bot.answer.one {
  display: flex;
  justify-content: flex-start;  
  align-items: flex-start;  
  gap: 0.8rem;  /*调整间距 */
}

.bot.answer.one span {
  background: white;
  color: #333;
  padding: 1rem;
  border-radius: 0 1rem 1rem 1rem;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  max-width: 85%;
  line-height: 1.5;
  position: relative;
}

.user.question {
  display: flex;
  justify-content: flex-end;
  align-items: flex-start;
  gap: 0.8rem;
}
.user.question span {
  background: #2563EB;
  color: white;
  padding: 1rem;
  border-radius: 1rem 0 1rem 1rem;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  max-width: 85%;
  line-height: 1.5;
}

/* 角色标签 */
.bot.answer::before,
.user.question::before {
  content: attr(data-role);
  font-size: 0.8rem;
  color: #999;
  position: absolute;
  top: -1.2rem;
}

/* 加载动画 */
.van-loading {
  padding: 2rem;
  text-align: center;
  color: #666;
}
.van-icon-star-o {
  color: #2563EB;
  animation: spin 1.5s linear infinite;
}

@keyframes spin {
  100% { transform: rotate(360deg); }
}

.ft {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 1rem;
  border-top: 1px solid #eee;
  box-shadow: 0 -2px 10px rgba(0,0,0,0.05);
}

.input {
  display: flex;
  gap: 0.5rem;
  max-width: 800px;
  margin: 0 auto;
}

.input input {
  flex: 1;
  padding: 0.8rem 1.2rem;
  border: 1px solid #ddd;
  border-radius: 2rem;
  font-size: 1rem;
  background: #f8f9fa;
  transition: all 0.2s;
}

.input input:focus {
  outline: none;
  border-color: #2563EB;
  background: white;
  box-shadow: 0 0 0 3px rgba(142, 111, 247, 0.1);
}

.input button {
  padding: 0.8rem 1.5rem;
  background: #2563EB;
  color: white;
  border: none;
  border-radius: 2rem;
  font-weight: 500;
  cursor: pointer;
  transition: opacity 0.2s;
}

.input button:active {
  opacity: 0.8;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .bd {
    padding: 0.5rem 0.5rem 4rem;
    height: calc(100vh - 115px);
  }
  
  .bot.answer span,
  .user.question span {
    max-width: 90%;
    font-size: 0.9rem;
    padding: 0.8rem;
  }
  
  .ft {
    padding: 0.8rem;
  }
  
  .input input {
    padding: 0.7rem 1rem;
    font-size: 0.9rem;
  }
  
  .input button {
    padding: 0.7rem 1.2rem;
  }
}


/* 题目容器样式 */
.question-item {
  margin: 20px 0px 20px 34px;
  padding: 15px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.sure{
  margin: 20px 0px 20px 34px;
}

/* 选择题选项样式 */
.choice ul {
  list-style: none;
  padding-left: 20px;
}

.choice li {
  margin: 8px 0;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 4px;
}

/* 填空题下划线样式 */
.blank h3 {
  font-family: 'Courier New', monospace;
}

/* 答案突出显示 */
.correct {
  color: #1890ff;
  font-weight: bold;
}

/* 解析样式 */
.explanation {
  margin-top: 10px;
  padding: 10px;
  background: #f3f4f6;
  border-radius: 4px;
  font-size: 0.9em;
}

/* 加载中占位符 */
.generating-placeholder {
  color: #666;
  text-align: center;
  padding: 20px;
}
</style>